package de.breitbeil.jbooking.ui.dialog;

import java.util.List;

import org.springframework.richclient.dialog.FormBackedDialogPage;
import org.springframework.richclient.dialog.TitledPageApplicationDialog;
import org.springframework.richclient.form.Form;
import org.springframework.richclient.settings.SettingsException;
import org.springframework.richclient.settings.SettingsManager;

import de.breitbeil.jbooking.task.ExcelExportTask;
import de.breitbeil.jbooking.ui.form.ExcelExportForm;
import de.breitbeil.jbooking.ui.form.ExcelExportFormObject;

public class ExcelExportDialog extends TitledPageApplicationDialog {

    public static final String ID = "excelExportDialog"; 

    private Form form;
    private List<Object> objects;
    private SettingsManager settingsManager;
    private List<String> availableProperties;

    public ExcelExportDialog(String entity, SettingsManager settingsManager, List<Object> objects, List<String> availableProperties) throws SettingsException {
        ExcelExportFormObject formObject = new ExcelExportFormObject(entity);
        formObject.init(settingsManager.getUserSettings());
        
        form = new ExcelExportForm(formObject, availableProperties);
        this.settingsManager = settingsManager;
        this.availableProperties = availableProperties;
        this.objects = objects;
        
        setDialogPage(new FormBackedDialogPage(form));
    }
    
    protected void onInitialized() {
        super.onInitialized();

        setTitle(getMessage(ID + ".title"));
        setTitlePaneTitle(getMessage(ID + ".title"));
        setDescription(getMessage(ID + ".description"));

        setResizable(false);
    }
    
    @Override
    protected boolean onFinish() {
        form.commit();
        ExcelExportFormObject formObject = (ExcelExportFormObject) form.getFormObject();
        
        try {
            formObject.save(settingsManager.getUserSettings());
        } catch (SettingsException e) {
            throw new RuntimeException("Can't save settings", e);
        }
        
        //ExcelExportTask exportTask = new ExcelExportTask(objects, formObject.getProperties()); 
        ExcelExportTask exportTask = new ExcelExportTask(objects, availableProperties, formObject.getFilename());
        exportTask.execute();
        
        
        return true;
    }

}
